package com.ruoyi.web.service;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class C2PipelineRunningStatusService {

    @Autowired
    private DruidDataSource druidDataSource;

    public Map<String, Map<String, Object>> getCICDStatistics() {
        // 获取当天的日期，作为查询条件
        String todayStart = LocalDate.now().atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String todayEnd = LocalDate.now().plusDays(1).atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // 构造 SQL 查询语句
        String sql = "SELECT `cicdName`, `isIntegrated`, `versionNo`, `timeLeft`, COUNT(*) AS `count` " +
                "FROM `c2_cicd_info` " +
                "WHERE `buildTime` >= ? AND `buildTime` < ? " +
                "GROUP BY `cicdName`, `isIntegrated`, `versionNo`, `timeLeft`";

        // 存储统计结果
        Map<String, Map<String, Object>> statistics = new HashMap<>();

        try (Connection conn = druidDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 设置参数
            stmt.setString(1, todayStart);
            stmt.setString(2, todayEnd);

            // 执行查询并处理结果
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    String cicdName = rs.getString("cicdName");
                    int isIntegrated = rs.getInt("isIntegrated");
                    String versionNo = rs.getString("versionNo");
                    String timeLeft = rs.getString("timeLeft");
                    int count = rs.getInt("count");

                    // 初始化统计数据
                    statistics.putIfAbsent(cicdName, new HashMap<>());
                    Map<String, Object> cicdStats = statistics.get(cicdName);

                    if (isIntegrated == 0) {
                        // 更新完成版本数量（可能需要累加）
                        cicdStats.put("completed", count + (int) cicdStats.getOrDefault("completed", 0));
                    } else if (isIntegrated == 1) {
                        // 初始化计划版本列表
                        cicdStats.putIfAbsent("planned", new ArrayList<Map<String, String>>());
                        @SuppressWarnings("unchecked")
                        List<Map<String, String>> plannedVersions = (List<Map<String, String>>) cicdStats.get("planned");

                        // 插入计划版本
                        Map<String, String> plannedData = new HashMap<>();
                        plannedData.put("versionNo", versionNo);
                        plannedData.put("timeLeft", timeLeft);
                        plannedVersions.add(plannedData);
                    }
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return statistics;
    }
}

